#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import threading
import time
from threading import Thread

import requests
from contextlib import closing

from utils.ThreadUtils import asyncCall


class DownloadRate(object):
    # uuid
    id = str
    # 目标值
    ariaValuemax = int
    # 当前值
    ariaValuenow = int

    def __init__(self, id=None, ariaValuenow=0, ariaValuemax=0):
        self.id = id
        self.ariaValuenow = ariaValuenow
        self.ariaValuemax = ariaValuemax

# 获取大小
def getContentSize(url):
    response = requests.head(url);
    content_size = int(response.headers['content-length'])  # 内容体总大小
    return content_size;


# 文件下载器
def newDownload(file_url, file_path):
    content_size = getContentSize(file_url)
    asyncDown(file_url, file_path)
    return content_size


@asyncCall
def asyncDown(file_url, file_path):
    with closing(requests.get(file_url, stream=True)) as response:
        content_size = int(response.headers['content-length'])  # 内容体总大小
        chunk_size = 1024  # 单次请求最大值
        data_count = 0
        with open(file_path, "wb") as file:
            for data in response.iter_content(chunk_size=chunk_size):
                file.write(data)
                data_count = data_count + len(data)
                now_jd = (data_count / content_size) * 100
                print("\r 文件下载进度：%d%%(%d/%d) - %s" % (now_jd, data_count, content_size, file_path), end=" ")
